package com.senjoeson.teamfriends.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.bean.Friend;
import com.senjoeson.teamfriends.bean.Message;
import com.senjoeson.teamfriends.bean.MessageTypeUtils;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.utils.ALog;
import com.senjoeson.teamfriends.utils.GlideUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 主要处理添加好友操作的类
 */
public class AddFriendMessageActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.portrait)
    CircleImageView mPortrait;
    @BindView(R.id.realname)
    TextView mRealname;
    @BindView(R.id.telephone)
    TextView mTelephone;
    @BindView(R.id.wechat)
    TextView mWechat;
    @BindView(R.id.city)
    TextView mCity;
    @BindView(R.id.school)
    TextView mSchool;
    @BindView(R.id.hobbies)
    TextView mHobbies;
    @BindView(R.id.sign)
    TextView mSign;
    @BindView(R.id.doSomething)
    Button mDoSomething;  //接受好友申请，拒绝好友申请 ，好友申请成功
    @BindView(R.id.refuse)
    Button mRefuse;
    public User mUser;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend_message);
        ButterKnife.bind(this);

        //检查消息类型是什么？
        final int mMessageType = getIntent().getIntExtra("MessageType", -1);
        String messageId = getIntent().getStringExtra("messageId");
        BmobQuery<Message> messageBmobQuery = new BmobQuery<>();
        messageBmobQuery.getObject(messageId, new QueryListener<Message>() {
            @Override
            public void done(Message message, BmobException e) {
                initData(message);
                User currentUser = BmobUser.getCurrentUser(User.class);
                initListens(currentUser, message, mMessageType);
            }
        });

    }

    /**
     * 初始化消息
     *  从消息拿到是谁给你发的消息
     * @param message 消息
     */
    private void initData(Message message) {
        String other_userid = message.getOther_userid();
        BmobQuery<User> query = new BmobQuery<>();
        query.getObject(other_userid, new QueryListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e == null) {
                    mUser = user;
                    setData(user);
                } else {
                    ALog.d("用户信息获取失败");
                }
            }
        });
    }

    /**
     * 获取对方信息
     * 设置进去
     *
     * @param user user对象  可以获得个人信息
     */
    private void setData(User user) {
        mRealname.setText(user.getRealName());
        mCity.setText(user.getCity());
        mSchool.setText(user.getSchool());
        mSign.setText(user.getSign());
        mWechat.setText(user.getWeChat());
        mTelephone.setText(user.getTelephone());
        mHobbies.setText(user.getHobbies().toString());
        GlideUtils.loadImage(AddFriendMessageActivity.this, user.getPortrait().getFileUrl(), mPortrait);

    }

    /**
     * 初始化一些监听
     *
     * @param currentUser  当前登录的用户
     * @param localMessage 本地消息  就是得到当前的消息
     * @param messageType  根据判断消息类型 做出反应
     */
    private void initListens(final User currentUser, final Message localMessage, int messageType) {

        switch (messageType) {
            case MessageTypeUtils.MESSGE_APPLY_FRIEND_STATE:     //当提出好友申请时
                mDoSomething.setText("同意好友申请");
                mDoSomething.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //把对方添加到自己的好友列表中
                        addFriend(mUser, currentUser.getObjectId());
                        solveMessage(localMessage);
                        // 还需要把你添加到对方的好友之中,还有给对方发送一条消息表示我已经同意对方申请
                        addFriend(currentUser, mUser.getObjectId());
                        sendMessageToOther(mUser.getObjectId(), currentUser, MessageTypeUtils.MESSGE_APPLY_FRIEND_PASS);
                        onBackPressed();
                    }
                });
                mRefuse.setVisibility(View.VISIBLE);
                mRefuse.setText("忽略好友申请");
                mRefuse.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        solveMessage(localMessage);     //直接删掉消息 不理会
                        sendMessageToOther(mUser.getObjectId(), currentUser, MessageTypeUtils.MESSGE_APPLY_FRIEND_REFUSE);
                        onBackPressed();
                    }
                });
                break;
            case MessageTypeUtils.MESSGE_APPLY_FRIEND_REFUSE:
                mDoSomething.setText("对方已拒绝好友申请");
                mRefuse.setVisibility(View.GONE);
                mDoSomething.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        solveMessage(localMessage);
                        onBackPressed();
                    }
                });

                break;
            case MessageTypeUtils.MESSGE_APPLY_FRIEND_PASS:
                mDoSomething.setText("对方已同意您的好友申请");
                mRefuse.setVisibility(View.GONE);
                mDoSomething.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        solveMessage(localMessage);
                        onBackPressed();
                    }
                });
                break;
            case MessageTypeUtils.MESSGE_HELP:
                break;
        }

    }

    /**
     * 把user添加到otherid的好友之中
     *
     * @param user
     * @param otherid
     */
    public void addFriend(final User user, final String otherid) {
        final Friend friend = new Friend();
        friend.setUserid(otherid);
        BmobQuery<Friend> friendBmobQuery = new BmobQuery<>();
        friendBmobQuery.addWhereEqualTo("userid", otherid);
        friendBmobQuery.addWhereEqualTo("nickname", user.getNickname());
        friendBmobQuery.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if (list == null || list.size() == 0) {
                    friend.setNickname(user.getNickname());
                    friend.setGender(user.getGender());
                    friend.setCity(user.getCity());
                    friend.setHobbies(user.getHobbies());
                    friend.setLatLng(user.getLatLng());
                    friend.setPortrait(user.getPortrait());
                    friend.setTelephone(user.getTelephone());
                    friend.setWeChat(user.getWeChat());
                    friend.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                ALog.d("添加好友成功");
                            } else {
                                ALog.d(e.getMessage());
                            }

                        }
                    });
                } else {
                    ALog.d("添加失败,已存在该好友");

                }
            }
        });

    }

    /**
     * 处理消息,目前的方式是 从列表中删除
     *
     * @param localMessage
     */
    private void solveMessage(Message localMessage) {
        if (localMessage != null) {
            localMessage.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ALog.d("删除成功");
                    } else {
                        ALog.d("删除不成功");
                    }
                }
            });
        }
    }

    /**
     * 给对方发消息
     *
     * @param otherid 接收方
     * @param user    消息发送方
     */
    private void sendMessageToOther(String otherid, User user, int messageType) {
        Message message = new Message();
        message.setUserid(otherid);
        message.setSolve(false);
        message.setMessageType(messageType);
        message.setNickname(user.getNickname());
        message.setContent(user.getNickname() + "已经同意你的好友申请");
        message.setMessagetime(System.currentTimeMillis());
        message.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    ALog.d("消息发送成功");
                } else {
                    ALog.d(e.getMessage());
                }
            }
        });
    }

}
